package com.campus.help.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.help.entity.Banner;
import com.campus.help.mapper.BannerMapper;
import com.campus.help.service.BannerService;
import com.campus.help.utils.FileStorageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 轮播图服务实现类
 */
@Service
@Slf4j
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner> implements BannerService {

    @Autowired
    private FileStorageUtils fileStorageUtils;

    @Override
    public IPage<Banner> getBannerPage(Page<Banner> page, String keyword, Integer status) {
        LambdaQueryWrapper<Banner> queryWrapper = new LambdaQueryWrapper<>();

        // 关键词搜索
        if (StringUtils.hasText(keyword)) {
            queryWrapper.and(wrapper -> wrapper
                .like(Banner::getTitle, keyword)
                .or()
                .like(Banner::getDescription, keyword)
            );
        }

        // 状态筛选
        if (status != null) {
            queryWrapper.eq(Banner::getStatus, status);
        }

        // 按排序值和创建时间排序
        queryWrapper.orderByAsc(Banner::getSortOrder)
                   .orderByDesc(Banner::getCreateTime);

        IPage<Banner> bannerPage = this.page(page, queryWrapper);

        // 为每个轮播图生成图片访问URL
        bannerPage.getRecords().forEach(banner -> {
            if (StringUtils.hasText(banner.getImageUrl())) {
                try {
                    // 检查是否已经是完整的URL
                    if (banner.getImageUrl().startsWith("http://") || banner.getImageUrl().startsWith("https://")) {
                        // 已经是完整URL，直接使用
                        log.info("轮播图已使用完整URL: {}", banner.getImageUrl());
                    } else {
                        // 生成文件访问URL
                        String fileUrl = fileStorageUtils.getFileUrl(banner.getImageUrl());
                        banner.setImageUrl(fileUrl);
                        log.info("轮播图生成文件访问URL: {} -> {}", banner.getImageUrl(), fileUrl);
                    }
                } catch (Exception e) {
                    log.error("生成轮播图URL失败: {}", banner.getImageUrl(), e);
                    // 使用默认图片或设置为null
                    banner.setImageUrl("https://via.placeholder.com/750x300/667eea/ffffff?text=" + banner.getTitle());
                }
            } else {
                // 如果没有图片URL，使用默认图片
                banner.setImageUrl("https://via.placeholder.com/750x300/667eea/ffffff?text=" + banner.getTitle());
            }
        });

        return bannerPage;
    }

    @Override
    public boolean addBanner(Banner banner, MultipartFile imageFile) {
        try {
            // 上传图片
            if (imageFile != null && !imageFile.isEmpty()) {
                String fileName = fileStorageUtils.uploadFile(imageFile, "banners");
                banner.setImageUrl(fileName);
            }

            // 设置默认值
            if (banner.getSortOrder() == null) {
                banner.setSortOrder(0);
            }
            if (banner.getStatus() == null) {
                banner.setStatus(1);
            }

            return this.save(banner);
        } catch (Exception e) {
            throw new RuntimeException("添加轮播图失败：" + e.getMessage());
        }
    }

    @Override
    public boolean updateBanner(Banner banner, MultipartFile imageFile) {
        try {
            // 如果上传了新图片，删除旧图片并上传新图片
            if (imageFile != null && !imageFile.isEmpty()) {
                // 获取旧图片信息
                Banner oldBanner = this.getById(banner.getId());
                if (oldBanner != null && StringUtils.hasText(oldBanner.getImageUrl())) {
                    // 只删除相对路径，不删除完整URL
                    if (!oldBanner.getImageUrl().startsWith("http://") && !oldBanner.getImageUrl().startsWith("https://")) {
                        fileStorageUtils.deleteFile(oldBanner.getImageUrl());
                    }
                }

                // 上传新图片
                String fileName = fileStorageUtils.uploadFile(imageFile, "banners");
                banner.setImageUrl(fileName);
            }

            return this.updateById(banner);
        } catch (Exception e) {
            throw new RuntimeException("更新轮播图失败：" + e.getMessage());
        }
    }

    @Override
    public boolean deleteBanner(Long id) {
        try {
            // 获取轮播图信息
            Banner banner = this.getById(id);
            if (banner != null && StringUtils.hasText(banner.getImageUrl())) {
                // 只删除相对路径，不删除完整URL
                if (!banner.getImageUrl().startsWith("http://") && !banner.getImageUrl().startsWith("https://")) {
                    fileStorageUtils.deleteFile(banner.getImageUrl());
                }
            }

            return this.removeById(id);
        } catch (Exception e) {
            throw new RuntimeException("删除轮播图失败：" + e.getMessage());
        }
    }

    @Override
    public boolean toggleStatus(Long id, Integer status) {
        Banner banner = new Banner();
        banner.setId(id);
        banner.setStatus(status);
        return this.updateById(banner);
    }
}
